package club.janna.netty.pipeline;


import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

public class InboundPipelineDemo {
    public static void main(String[] args) throws InterruptedException {
        EventLoopGroup boosGroup = new NioEventLoopGroup(1);
        EventLoopGroup workGroup = new NioEventLoopGroup();

        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(boosGroup, workGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline pipeline = ch.pipeline();
                        pipeline.addLast(new InboundHandlerA());
                        pipeline.addLast(new InboundHandlerB());
                        pipeline.addLast(new InboundHandlerC());
                    }
                });
        ChannelFuture future = bootstrap.bind(8080).sync();
        System.out.println("启动完成，8080");
        future.channel().closeFuture().sync();

        boosGroup.shutdownGracefully();
        workGroup.shutdownGracefully();
    }

    private static class InboundHandlerA extends ChannelInboundHandlerAdapter {
        @Override
        public void channelActive(ChannelHandlerContext ctx) throws Exception {
            System.out.println("InboundHandlerA active");
            ctx.fireChannelActive();
            ctx.pipeline().fireChannelRead("Hello, World!");
        }

        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            System.out.println("InboundHandlerA receive -> " + msg);
            ctx.fireChannelRead(msg);
        }
    }

    private static class InboundHandlerB extends ChannelInboundHandlerAdapter {
        @Override
        public void channelActive(ChannelHandlerContext ctx) throws Exception {
            System.out.println("InboundHandlerB active");
            ctx.fireChannelActive();
        }

        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            System.out.println("InboundHandlerB receive -> " + msg);
            ctx.fireChannelRead(msg);
        }
    }

    private static class InboundHandlerC extends ChannelInboundHandlerAdapter {
        @Override
        public void channelActive(ChannelHandlerContext ctx) throws Exception {
            System.out.println("InboundHandlerC active");
            ctx.fireChannelActive();
        }

        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            System.out.println("InboundHandlerC receive -> " + msg);
            ctx.fireChannelRead(msg);
        }
    }
}
